import {ColorError} from './error';
import {UserBaseConfig} from "../config"
// 合并 配置
function margeconfig(oldConfig: any, newConfig: any) {
	let res: any = {};
	if (typeof oldConfig !== 'object' && typeof newConfig !== 'object') {
		if (typeof newConfig === null || typeof newConfig === undefined) {
			return oldConfig;
		} else {
			if (typeof newConfig === typeof oldConfig) {
				return newConfig;
			} else {
				console.log(oldConfig, '的类型错误，请根据指定类型填写配置');
				return oldConfig;
			}
		}
	}
	for (let key in oldConfig) {
		if(oldConfig.hasOwnProperty(key)) {
			if (
				typeof newConfig[key] === 'object' &&
				newConfig[key] !== null &&
				typeof oldConfig[key] === 'object' &&
				oldConfig[key] !== null
			) {
				if(key === 'userList'){
					res[key] = JSON.parse(JSON.stringify(newConfig[key]));
				} else if (key === 'userBaseLogs'){
					res[key] = margeUserConfig(newConfig.userList.map((item:{name:string})=>item.name) ,newConfig[key])
				} else {
					res[key] = margeconfig(oldConfig[key], newConfig[key]);
				}
			} else if (
				typeof oldConfig[key] !== 'object' &&
				typeof newConfig[key] !== 'object'
			) {
				if (
					typeof newConfig[key] === null ||
					typeof newConfig[key] === undefined
				) {
					res[key] = oldConfig[key];
				} else {
					if (typeof newConfig[key] === typeof oldConfig[key]) {
						res[key] = newConfig[key];
					} else {
						res[key] = oldConfig[key];
					}
				}
			} else {
				res[key] = oldConfig[key];
			}
		}
	}
	return res;
}
function margeUserConfig(userList:Array<string>, newConfig: any) {
	let res:any = {};
	for (let key in newConfig) {
		if(newConfig.hasOwnProperty(key)){
			if (userList.includes(key)) {
				res[key] = margeconfig(UserBaseConfig, JSON.parse(JSON.stringify(newConfig[key])));
			}
		}
	}
	return res;
}
// 比较两个对象是否相等
function compareObject(obj1: any, obj2: any) {
	try {
		if (typeof obj1 !== 'object' && typeof obj2 !== 'object') {
			return obj1 === obj2;
		}
		if (Object.keys(obj1).length !== Object.keys(obj2).length) {
			return false;
		}
		for (let key in obj1) {
			if (!compareObject(obj1[key], obj2[key])) {
				return false;
			}
		}
	} catch (error) {
		return false;
	}
	return true;
}
function drawCross(ctx: any, canvas: any) {
	ctx.fillStyle = 'red';
	// 第一条线，从左上到右下
	ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布内容
	ctx.strokeStyle = 'red'; // 设置线条颜色为红色
	ctx.lineWidth = 2; // 设置线条宽度

	// 设置线条两端和交汇处的样式为圆形
	ctx.lineCap = 'round';
	ctx.lineJoin = 'round';

	// 绘制圆圈
	ctx.beginPath();
	ctx.arc(10, 10, 8, 0, Math.PI * 2); // 圆心为 (10, 10)，半径为 8
	ctx.stroke();

	// 计算叉叉的位置，使其在圆圈内居中
	const offset = 4; // 设置叉叉相对于圆心的偏移量，让叉叉略小于圆圈
	const startX1 = 10 - offset,
		startY1 = 10 - offset; // 第一条斜线起点
	const endX1 = 10 + offset,
		endY1 = 10 + offset; // 第一条斜线终点
	const startX2 = 10 + offset,
		startY2 = 10 - offset; // 第二条斜线起点
	const endX2 = 10 - offset,
		endY2 = 10 + offset; // 第二条斜线终点

	// 绘制叉叉的第一条斜线
	ctx.beginPath();
	ctx.moveTo(startX1, startY1);
	ctx.lineTo(endX1, endY1);
	ctx.stroke();

	// 绘制叉叉的第二条斜线
	ctx.beginPath();
	ctx.moveTo(startX2, startY2);
	ctx.lineTo(endX2, endY2);
	ctx.stroke();
}
// 定义 RGB 类型
interface RGB {
	r: number;
	g: number;
	b: number;
}

// 定义 HSL 类型
interface HSL {
	h: number;
	s: number;
	l: number;
}

// 将 HEX 转换为 RGB
function hexToRgb(hex: string) {
	// 去掉前面的 #
	hex = hex.replace(/^#/, '');

	// 判断输入的 hex 是否是三位（比如 #fff），如果是三位，将其转换为六位（#ffffff）
	if (hex.length === 3) {
		hex = hex
			.split('')
			.map((char) => char + char)
			.join('');
	}

	// 转换成 RGB 格式
	const bigint = parseInt(hex, 16);
	const r = (bigint >> 16) & 255;
	const g = (bigint >> 8) & 255;
	const b = bigint & 255;

	return {r, g, b};
}

// 定义 RGB 类型
interface RGB {
	r: number;
	g: number;
	b: number;
}

// 定义 HSL 类型
interface HSL {
	h: number;
	s: number;
	l: number;
}

// 将颜色名称转换为 RGB 格式
function colorNameToRgb(colorName: string): RGB {
	// 创建一个虚拟 DOM 元素
	const fakeDiv = document.createElement('div');
	fakeDiv.style.color = colorName;
	document.body.appendChild(fakeDiv);

	// 获取计算后的颜色值 (RGB 格式)
	const computedColor = getComputedStyle(fakeDiv).color;
	document.body.removeChild(fakeDiv);

	// 如果 computedColor 是 "rgba(0, 0, 0, 0)" 或类似值，说明颜色无效
	if (
		computedColor === 'rgba(0, 0, 0, 0)' ||
		computedColor === 'transparent'
	) {
		throw new ColorError(`Invalid color name: ${colorName}`);
	}

	// 转换 "rgb(r, g, b)" 字符串格式为 RGB 对象格式
	const rgbValues = computedColor.match(/\d+/g)?.map(Number);
	if (!rgbValues || rgbValues.length < 3) {
		throw new ColorError(`Unable to parse color name: ${colorName}`);
	}

	return {r: rgbValues[0], g: rgbValues[1], b: rgbValues[2]};
}

// 将 RGB 转换为 HSL
function rgbToHsl(r: number, g: number, b: number): HSL {
	// 检查 RGB 值是否在有效范围内
	if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) {
		throw new ColorError(
			`Invalid RGB values: { r: ${r}, g: ${g}, b: ${b} }. Each value must be in the range 0-255.`,
		);
	}

	r /= 255;
	g /= 255;
	b /= 255;

	const max = Math.max(r, g, b);
	const min = Math.min(r, g, b);
	let h = 0,
		s = 0,
		l = (max + min) / 2;

	if (max !== min) {
		const d = max - min;
		s = l > 0.5 ? d / (2 - max - min) : d / (max + min);

		switch (max) {
			case r:
				h = (g - b) / d + (g < b ? 6 : 0);
				break;
			case g:
				h = (b - r) / d + 2;
				break;
			case b:
				h = (r - g) / d + 4;
				break;
		}
		h /= 6;
	}

	return {h, s, l};
}

// 将 HSL 转换为 RGB
function hslToRgb(h: number, s: number, l: number): RGB {
	// 检查 HSL 值是否在有效范围内
	if (h < 0 || h > 1 || s < 0 || s > 1 || l < 0 || l > 1) {
		throw new ColorError(
			`Invalid HSL values: { h: ${h}, s: ${s}, l: ${l} }. Each value must be in the range 0-1.`,
		);
	}

	let r: number, g: number, b: number;

	if (s === 0) {
		r = g = b = l; // Achromatic
	} else {
		const hue2rgb = (p: number, q: number, t: number): number => {
			if (t < 0) t += 1;
			if (t > 1) t -= 1;
			if (t < 1 / 6) return p + (q - p) * 6 * t;
			if (t < 1 / 2) return q;
			if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
			return p;
		};

		const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
		const p = 2 * l - q;
		r = hue2rgb(p, q, h + 1 / 3);
		g = hue2rgb(p, q, h);
		b = hue2rgb(p, q, h - 1 / 3);
	}

	return {
		r: Math.round(r * 255),
		g: Math.round(g * 255),
		b: Math.round(b * 255),
	};
}

// 将 RGB 转换为 HEX 格式
function rgbToHex(r: number, g: number, b: number): string {
	// 检查 RGB 值是否在有效范围内
	if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) {
		throw new ColorError(
			`Invalid RGB values: { r: ${r}, g: ${g}, b: ${b} }. Each value must be in the range 0-255.`,
		);
	}

	return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`;
}

// 计算亮色的函数
function getLighterColor(
	colorName: string,
	lightnessFactor: number = 0.2,
): string {
	// 校验 lightnessFactor 是否在有效范围内
	if (lightnessFactor < 0 || lightnessFactor > 1) {
		throw new ColorError(
			`Invalid lightnessFactor: ${lightnessFactor}. The value must be in the range 0-1.`,
		);
	}
	let r, g, b;
	if (colorName.startsWith('#')) {
		const RgB = hexToRgb(colorName);
		r = RgB.r;
		g = RgB.g;
		b = RgB.b;
	} else {
		colorName = colorName.toLowerCase();
		// 1. 将颜色名称转换为 RGB
		const RgB = colorNameToRgb(colorName);
		r = RgB.r;
		g = RgB.g;
		b = RgB.b;
	}

	// 2. 将 RGB 转换为 HSL
	let {h, s, l} = rgbToHsl(r, g, b);

	// 3. 增加亮度
	l = Math.min(l + lightnessFactor, 1); // 确保亮度值不会超过 1

	// 4. 将 HSL 转换回 RGB
	const {r: newR, g: newG, b: newB} = hslToRgb(h, s, l);

	// 5. 将 RGB 转换为 HEX
	return rgbToHex(newR, newG, newB);
}

function formatData(obj: any,maxDeep = 12,intend = 0) {
	const spacing = '  '; // 用两个空格作为缩进
    let result = '';
	if(typeof obj !== "object" && typeof obj !== "function"){
		return obj.toString();
	}
    if(intend < maxDeep){
        if(Array.isArray(obj)){
            result += "[\n";
        } else {
            result += "{\n";
        }
        for (const key in obj) {
            if(obj.hasOwnProperty(key)){
                result += spacing.repeat(intend+1) + key + ": ";
                if(typeof obj[key] === "object" && obj[key] !== null){
                    result += formatData(obj[key], maxDeep, intend + 1);
                } else {
                    //如果是普通值
                    result += obj[key]
                }
                result += ',\n'; // 添加逗号和换行
            }
        }
        //去掉最后一个逗号
        if(result.endsWith(",\n")){
            result = result.slice(0, -2);
        }
        result += "\n" + spacing.repeat(intend);
    
        if(Array.isArray(obj)){
            result += "]";
        } else {
            result += "}";
        }
    } else {
        result+= ".... "
    }
	return result;
}

export {margeconfig, getLighterColor, compareObject, drawCross, formatData};
